package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.atguigu.spzx.exception.BaseException;
import com.atguigu.spzx.manager.listener.ExcelListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.manager.service.ICategoryService;
import com.atguigu.spzx.model.vo.common.entity.product.Category;
import com.atguigu.spzx.model.vo.common.vo.product.CategoryExcelVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author 宋哥
 * @since 2024-01-13
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 将id作为parentId,查询以id作为父节点的product分类
     * @param id
     * @return
     */
    public List<Category> findCategoriesById(Long id) {
        //将id作为parentId,查询以id作为父节点的product分类
        List<Category> categoryList = categoryMapper
                .selectList(new LambdaQueryWrapper<Category>()
                        .eq(id != null, Category::getParentId, id));
        //遍历集合，判断一下是否存在孩子节点
        if(CollectionUtil.isEmpty(categoryList)){
            //返回空集合
            return Collections.emptyList();
        }
        //非空
        categoryList.forEach(node->{
            //查询当前节点是否在下个节点,select count(*) from where parent_id=id;
            Long count = categoryMapper
                    .selectCount(new LambdaQueryWrapper<Category>()
                            .eq(node.getId() != null, Category::getParentId, node.getId()));
            if(count>0){
                        //count>0,存在,将字段HasChildren设置为true
                        node.setHasChildren(true);
                    }
                }
        );
        //返回结果
        return categoryList;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        try {

            // 设置响应结果类型
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("分类数据", StandardCharsets.UTF_8);
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

            // 查询数据库中的数据
            List<Category> categoryList = list();
            List<CategoryExcelVo> categoryExcelVoList = new ArrayList<>(categoryList.size());

            // 将从数据库中查询到的Category对象转换成CategoryExcelVo对象
            for(Category category : categoryList) {
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
                BeanUtils.copyProperties(category, categoryExcelVo, CategoryExcelVo.class);
                categoryExcelVoList.add(categoryExcelVo);
            }

            // 写出数据到浏览器端
            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class).sheet("分类数据").doWrite(categoryExcelVoList);

        } catch (IOException e) {
            throw new BaseException("数据导出异常");
        }
    }

    /**
     * 导入数据
     * @param file
     */
    @Transactional
    public void importData(MultipartFile file) {
        try {
            //创建监听器对象，传递mapper对象
//            ExcelListener<CategoryExcelVo> excelListener = new ExcelListener<>(categoryMapper);
            //调用read方法读取excel数据
            EasyExcel.read(file.getInputStream(),
                    CategoryExcelVo.class,new ExcelListener(categoryMapper)
                    ).sheet().doRead();
        } catch (IOException e) {
            throw new BaseException("导入异常");
        }
    }
}
